package com.jmu.edu.IMApplication.fragment;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.jmu.edu.IMApplication.MainActivity;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.event.LoginEvent;
import com.jmu.edu.IMApplication.utils.LoginUtils;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;
import com.wang.avi.AVLoadingIndicatorView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.jpush.im.api.BasicCallback;

import static android.content.Context.MODE_PRIVATE;

/**
 * @author ygc
 */
public class LoginFragment extends Fragment {

    private EditText nameText, passwordText;
    private ToggleButton passwordToggleButton;
    private ToggleButton nameToggleButton;
    private MaterialButton loginButton, registerButton;
    private SharedPreferences preferences;
    private ShapeableImageView avatarImage;
    private AVLoadingIndicatorView animation;

    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);

        nameText = view.findViewById(R.id.fragment_login_name);
        passwordText = view.findViewById(R.id.fragment_login_password);
        nameToggleButton = view.findViewById(R.id.fragment_login_nameToggleButton);
        passwordToggleButton = view.findViewById(R.id.fragment_login_passwordToggleButton);
        loginButton = view.findViewById(R.id.fragment_login_loginButton);
        avatarImage = view.findViewById(R.id.user_login_avatar);
        animation = view.findViewById(R.id.fragment_login_animation);
        registerButton = view.findViewById(R.id.fragment_login_register);

        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //在EventBus中注册
        EventBus.getDefault().register(this);
        //给登录按钮添加监听事件以及对应的动画
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickLogin();

            }
        });
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tag = "register";
                Fragment fragment = MyApplication.fragmentManager.findFragmentByTag(tag);
                if (fragment == null) {
                    fragment = new RegisterFragment();
                }
                ViewUtils.showFragment(fragment, tag, R.anim.from_right, R.anim.out_right);
            }
        });
        preferences = getContext().getSharedPreferences("UserInfo", MODE_PRIVATE);
        // 读取用户登录信息的列表
        //loadLoginMessageList();
        initNameAndPasswordText();

        // 点击下拉按钮可以展示出popupWindow来展示用户登录记录
        nameToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            }
        });

        nameText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        //是否显示密码按钮监听事件
        passwordToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //如果选中，显示密码
                    passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //否则隐藏密码
                    passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });


    }

    /**
     * 初始化密码框，如果之前有记住密码，则直接填入密码，否则填充空字符串
     */
    public void initNameAndPasswordText() {
        String username = preferences.getString("username", "");
        String password = preferences.getString("password", "");
        nameText.setText(username);
        passwordText.setText(password);
        if (username.equals("") || password.equals("")) {
            Log.d("登录界面", "preferences里面没有保存任何用户数据");
        } else {
            //根据判断当前是离线状态还是未登录状态来决定是否自动登录
            if (LoginUtils.isLogin()) {
                loginButton.callOnClick();
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {
        nameText.setText(event.getName());
        passwordText.setText(event.getPassword());
        //执行加载动画，并将loginButton隐藏（为了让加载动画占据loginButton的位置）
        animation.setVisibility(View.VISIBLE);
        loginButton.setVisibility(View.GONE);
        animation.show();
        //登录
        LoginUtils.login(event.getName(), event.getPassword(), new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {


                //这里说明登录成功，执行登录成功的代码
                if (i == 0) {
                    saveUsernameAndPassword(event.getName(), event.getPassword());
                    //更新头像,更新头像回调结束以后再移除登录界面
                    WillowUtils.updateUserAvatar(event.getAvatarFile(), new BasicCallback() {
                        @Override
                        public void gotResult(int i, String s) {
                            //关闭动画并重新显示loginButton
                            animation.hide();
                            loginButton.setVisibility(View.VISIBLE);
                            if (i != 0) {
                                if (event.getAvatarFile() != null) {
                                    Toast.makeText(getContext(), "上传头像失败，请检查权限设置或网络连接后再重新上传！", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                event.getAvatarFile().delete();
                            }
                            //将我这个用户设置为全局变量, 一定要在更新完头像以后再执行这个语句，否则无法获得最新的UserInfo
                            MyApplication.setUser(WillowUtils.getMyInfo());
                            //切换回MainActivity并执行初始化
                            MainActivity mainActivity = (MainActivity) getActivity();
                            mainActivity.initView();
                            //在EventBus中注销注册，因为已经用不到这个Fragment了
                            EventBus.getDefault().unregister(this);
                            //remove登录界面且手动释放内存
                            ViewUtils.removeFragment(LoginFragment.this);
                        }
                    });
                } else {
                    //执行登录失败的代码
                    Toast.makeText(getContext(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
                    passwordText.setText("");
                    passwordText.requestFocus();
                }
            }
        });
    }

    /**
     * 登录按钮点击事件
     */
    public void onClickLogin() {
        String username = nameText.getText().toString().trim();
        String password = passwordText.getText().toString().trim();

        // 判断账号或密码是否为空
        if ("".equals(username) || "".equals(password)) {
            Toast.makeText(getActivity(), "账号或密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        //执行加载动画，并将loginButton隐藏（为了让加载动画占据loginButton的位置）
        animation.setVisibility(View.VISIBLE);
        loginButton.setVisibility(View.GONE);
        animation.show();
        //登录
        LoginUtils.login(username, password, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                //关闭动画并重新显示loginButton
                animation.hide();
                loginButton.setVisibility(View.VISIBLE);

                //这里说明登录成功，执行登录成功的代码
                if (i == 0) {
                    saveUsernameAndPassword(username, password);
                    //将我这个用户设置为全局变量
                    MyApplication.setUser(WillowUtils.getMyInfo());
                    //切换回MainActivity并执行初始化
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.initView();
                    //在EventBus中注销注册，因为已经用不到这个Fragment了
                    EventBus.getDefault().unregister(this);
                    //remove登录界面且手动释放内存
                    ViewUtils.removeFragment(LoginFragment.this);
                } else {
                    //执行登录失败的代码
                    Toast.makeText(getContext(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
                    passwordText.setText("");
                    passwordText.requestFocus();
                }
            }
        });


//        // 因为最新的登录界面要添加在列表的最后一个，所以先遍历一遍列表，看看列表原来是否存在有这条记录，如果有则先删除
//        removeLoginMessage(username);
//        // 先设置用户名，密码要根据是否记住密码来设置
//        LoginMessage latestLoginMessage = new LoginMessage();
//        latestLoginMessage.setUsername(username);
//        // 将最新的登录记录存放进去，最新的登录记录放在列表最后一个
//        loginMessageArrayList.add(latestLoginMessage);
//        // 使用Gson将数组转换成json格式的字符串存储进去，然后提交保存


    }

    private void saveUsernameAndPassword(String username, String password) {
        //保存登录账号和密码
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        editor.putString("isAutoLogin", "no");
        editor.apply();
    }


//    public void hideOtherViews() {
//        passwordText.setVisibility(View.GONE);
//        passwordToggleButton.setVisibility(View.GONE);
//        passwordCheckBox.setVisibility(View.GONE);
//        loginButton.setVisibility(View.GONE);
//        loginButtonParentLayout.setVisibility(View.GONE);
//    }
//
//    public void showOtherViews() {
//        passwordText.setVisibility(View.VISIBLE);
//        passwordText.setEnabled(true);
//        passwordToggleButton.setVisibility(View.VISIBLE);
//        passwordCheckBox.setVisibility(View.VISIBLE);
//        loginButton.setVisibility(View.VISIBLE);
//        loginButtonParentLayout.setVisibility(View.VISIBLE);
//    }


//    public void showRememberedUser() {
//        View view = LayoutInflater.from(getContext()).inflate(R.layout.user_login_popup_window, null);
//        // 设置RecycleView
//        RecyclerView recyclerView = view.findViewById(R.id.user_login_select_recycle_view);
//        // 设置为垂直排列
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
//        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
//        recyclerView.setLayoutManager(linearLayoutManager);
//        //
//        LoginRecyclerViewAdapter loginAdapter = new LoginRecyclerViewAdapter(loginMessageArrayList, nameText, passwordText, avatarImage);
//        recyclerView.setAdapter(loginAdapter);
//        // linearLayout是登录界面中输入用户名输入部分的线性布局，popupWindow将在这个布局下面展示
//        LinearLayout linearLayout = getView().findViewById(R.id.fragment_login_username_layout);
//        // 第一个参数popupWindow的View，后面两个参数一个是宽度一个是高度
//        //PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//
//        PopupWindow popupWindow = new PopupWindow(view, linearLayout.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
//        // 设置获取焦点+可以获得点击事件
//        popupWindow.setFocusable(true);
//        popupWindow.setTouchable(true);
//        // 设置点击外部可以关掉
//        popupWindow.setOutsideTouchable(true);
//
//        // popupWindow创建好以后传入loginAdapter中
//        loginAdapter.setPopupWindow(popupWindow);
//
//        // 设置popupWindow消失时候的监听器，用来将nameToggleButton还原到noChecked状态
//        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                nameToggleButton.setChecked(false);
//                showOtherViews();
//            }
//        });
//        // 展示的位置位于linearLayout下方
//        popupWindow.showAsDropDown(linearLayout, 0, 50);
//
//
//    }
//
//    public void loadLoginMessageList() {
//        Type type = new TypeToken<List<LoginMessage>>() {
//        }.getType();
//        String loginMessageListJson = preferences.getString("userList", null);
//        /*
//          如果为空说明现在还没有存储任何用户登录信息
//          如果不为空那么通过Gson转化为用户登录信息的列表，以备使用
//         */
//        if (loginMessageListJson == null) {
//            loginMessageArrayList = new ArrayList<>();
//        } else {
//            loginMessageArrayList = new Gson().fromJson(loginMessageListJson, type);
//        }
//    }
//
//    /**
//     * 根据username，移除登录信息列表中对应的记录
//     *
//     * @param username
//     */
//    public void removeLoginMessage(String username) {
//        for (int i = 0; i < loginMessageArrayList.size(); i++) {
//            if (loginMessageArrayList.get(i).getUsername().equals(username)) {
//                loginMessageArrayList.remove(i);
//                break;
//            }
//        }
//    }

}